<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import {Plus, Edit, Delete, Search, Refresh} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from "axios";
import {usePagination} from "@@/composables/usePagination.js";
import {
  getResourceList,
  addResourceList,
  updateResourceList,
  deleteResourceList
} from "@@/apis/topicInfo/resourceManagement.js";

// 资源表格数据
const resources = ref([]);
const resourceDialogVisible = ref(false);
const resourceDialogTitle = ref('添加资源');
const currentResource = reactive({
  resourceName: '',
  resourceType: '文档',
  date: '',
  description: ''
});
const resourceFormRef = ref(null);
const resourceRules = ref({
  resourceName: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ],
  resourceType: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  date: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ]
});

const formData = reactive({
  resourceName: "",
  resourceType: ""
})
const searchFormRef = ref(null);

const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// 查询数据
function handleSearch() {
  getResourceListAPI();
}

// 重置表单
function resetSearch() {
  console.log('重置表单', searchFormRef);
  searchFormRef.value?.resetFields();
  handleSearch();
}


// 获取资源表格
function getResourceListAPI() {
  const formdata = new FormData();
  formdata.append('resourceName', formData.resourceName);
  formdata.append('page', paginationData.currentPage);
  formdata.append('size', paginationData.pageSize);
  getResourceList(formdata).then(res => {
    if(res.code === 200) {
      resources.value = res.data.records;
      paginationData.total = res.data.total;
    }
  })
}

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getResourceListAPI, { immediate: true })

// 初始化数据
onMounted(() => {

  // 模拟资源表格数据
  // resources.value = [
  //   {
  //     id: 1,
  //     name: '产品说明书V2.3',
  //     type: '文档',
  //     date: '2023-06-15',
  //     description: '详细介绍产品的功能、使用方法及注意事项'
  //   },
  //   {
  //     id: 2,
  //     name: '2023年度宣传视频',
  //     type: '视频',
  //     date: '2023-07-20',
  //     description: '公司品牌及产品宣传视频，时长3分钟'
  //   },
  //   {
  //     id: 3,
  //     name: '网站背景音乐合集',
  //     type: '音频',
  //     date: '2023-05-10',
  //     description: '网站各页面使用的背景音乐素材包'
  //   },
  //   {
  //     id: 4,
  //     name: '新产品形象图片集',
  //     type: '图片',
  //     date: '2023-08-05',
  //     description: '新产品多角度高清展示图片，含png和jpg格式'
  //   }
  // ];

  // 设置默认日期为今天
  currentResource.date = new Date().toISOString().split('T')[0];
});

// 获取资源标签类型
// const getResourceTagType = (type) => {
//   switch (type) {
//     case '文档':
//       return 'primary';
//     case '视频':
//       return 'success';
//     case '音频':
//       return 'warning';
//     case '图片':
//       return 'info';
//     default:
//       return 'default';
//   }
// };

// 资源表格操作
const handleAddResource = () => {
  resourceDialogTitle.value = '添加资源';
  // currentResource.id = null;
  currentResource.resourceName = '';
  currentResource.resourceType = '文档';
  currentResource.date = new Date().toISOString().split('T')[0];
  currentResource.description = '';
  resourceDialogVisible.value = true;
};

const handleEditResource = (row) => {
  resourceDialogTitle.value = '编辑资源';
  currentResource.resourceId = row.resourceId;
  currentResource.resourceName = row.resourceName;
  currentResource.resourceType = row.resourceType;
  currentResource.date = row.date;
  currentResource.description = row.description;
  resourceDialogVisible.value = true;
};

const handleDeleteResource = (id) => {
  ElMessageBox.confirm(
    '确定要删除这条资源吗？此操作不可撤销。',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger'
    }
  ).then(() => {
    deleteResourceList(id).then(res => {
      if(res.code === 200) {
        ElMessage.success('资源删除成功');
        // 重新获取信息资源列表
        getResourceListAPI();
      }
    })
  }).catch(() => {
    // 取消删除
  });
};

const handleSaveResource = () => {
  resourceFormRef.value.validate((valid) => {
    if (valid) {
      // console.log('currentResource', currentResource);
      // console.log('resourceDialogTitle', resourceDialogTitle);
      if(resourceDialogTitle.value === '添加资源') {
        const formData = new FormData();
        formData.append("resourceName", currentResource.resourceName)
        formData.append("resourceType", currentResource.resourceType)
        formData.append("date", currentResource.date)
        formData.append("description", currentResource.description)
        addResourceList(formData).then(res => {
          console.log('添加信息资源的结果是--->', res);
          if(res.code === 200) {
            ElMessage.success('资源添加成功');
            // 重新获取资源列表
            getResourceListAPI();
            resourceDialogVisible.value = false;
          }
        })
      }else {
        // 编辑资源
        // console.log('currentResource', currentResource);
        const formData = new FormData();
        formData.append("resourceId", currentResource.resourceId)
        formData.append("resourceName", currentResource.resourceName)
        formData.append("resourceType", currentResource.resourceType)
        formData.append("date", currentResource.date)
        formData.append("description", currentResource.description)
        updateResourceList(formData).then(res => {
          if(res.code === 200) {
            ElMessage.success('资源编辑成功');
            // 重新获取资源列表
            getResourceListAPI();
            resourceDialogVisible.value = false;
          }
        })
      }
    }
  });
};
</script>

<template>
  <div class="c">
    <div class="pane-header">
      <el-card>
        <el-form
          :model="formData"
          label-position="left"
          class="search-form"
          ref="searchFormRef"
          :inline="true"
        >
          <el-form-item prop="resourceName" label="名称">
            <el-input v-model="formData.resourceName" placeholder="请输入" />
          </el-form-item>
<!--          <el-form-item prop="resourceType" label="类型">-->
<!--            <el-input v-model="formData.resourceType" placeholder="请输入" />-->
<!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">
              查询
            </el-button>
            <el-button :icon="Refresh" @click="resetSearch">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <el-card>
      <el-button
        type="primary"
        icon="Plus"
        @click="handleAddResource"
      >
        添加资源
      </el-button>
<!--      <el-button-->
<!--        type="danger"-->
<!--        :icon="Delete"-->
<!--        @click="handleAddResource"-->
<!--      >-->
<!--        批量删除-->
<!--      </el-button>-->
      <el-table
        :data="resources"
        style="width: 100%"
      >
        <el-table-column
          prop="resourceId"
          label="ID"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="resourceName"
          label="名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="resourceType"
          label="类型"
          align="center"
        >
<!--          <template #default="scope">-->
<!--            <el-tag-->
<!--              :type="getResourceTagType(scope.row.type)"-->
<!--            >-->
<!--              {{ scope.row.type }}-->
<!--            </el-tag>-->
<!--          </template>-->
        </el-table-column>
        <el-table-column
          prop="date"
          label="日期"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="description"
          label="描述"
        ></el-table-column>
        <el-table-column
          label="操作"
          align="center"
        >
          <template #default="scope">
            <el-button
              type="primary"
              bg
              text
              size="small"
              @click="handleEditResource(scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              bg
              text
              size="small"
              @click="handleDeleteResource(scope.row.resourceId)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :current-page="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 资源表单弹窗 -->
    <el-dialog
      v-model="resourceDialogVisible"
      :title="resourceDialogTitle"
      width="500px"
    >
      <el-form
        :model="currentResource"
        ref="resourceFormRef"
        :rules="resourceRules"
        label-width="100px"
      >
        <el-form-item label="名称" prop="resourceName">
          <el-input v-model="currentResource.resourceName"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="resourceType">
          <el-select v-model="currentResource.resourceType">
            <el-option value="文档">文档</el-option>
            <el-option value="视频">视频</el-option>
            <el-option value="音频">音频</el-option>
            <el-option value="图片">图片</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="currentResource.date"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="currentResource.description"
            type="textarea"
            :rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resourceDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleSaveResource"
        >
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.tab-pane {
  height: 100%;
  padding: 20px;
}

.pane-header {
  margin-bottom: 20px;
}

.pane-header h2 {
  font-size: 18px;
  color: #34495e;
  font-weight: 600;
}

/* Element Plus 组件样式覆盖 */
::v-deep .el-table {
  margin-top: 10px;
}

::v-deep .el-dialog__body {
  padding: 20px;
}

::v-deep .el-textarea__inner {
  resize: vertical;
}

::v-deep .el-message-box {
  width: 100% !important;
  height: 100% !important;
}

.pager-wrapper {
  margin-top: 20px;
  text-align: right;
  display: flex;
  justify-content: flex-end;
}
</style>
